/**
 * 获取收款账户银行、支付平台名称
 *
*/
import { getBankList, getPaymentList } from '@/api/select';
import { createBank } from '@/api/setting';

export default {
  data() {
    return {
      bankList: [],
      bankListTemp: [],
      paymentList: [], // 支付平台
      flag: true// 获取银行列表重新渲染表格
    };
  },
  watch: {
    bankList: {
      handler(val) {
        if (val) {
          this.flag = false;
          this.$nextTick(() => {
            this.flag = true;
          });
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取银行名称列表
    getBankList() {
      getBankList().then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        res.data.forEach(el => {
          // eslint-disable-next-line no-sequences
          el.value = el.name,
          el.label = el.name;
        });
        this.bankList = res.data;
        this.bankListTemp = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取支付平台
    getPaymentList() {
      getPaymentList().then(res => {
        if (res.code === 200) {
          res.data.forEach(el => {
            // eslint-disable-next-line no-sequences
            el.value = el.name,
            el.label = el.name;
          });
          this.paymentList = res.data;
        }
      }).catch(err => console.error(err.message));
    },
    addNewBank(name) {
      this.$confirm('当前输入银行名称为系统未存在的银行，点击确定将自动添加该银行，请确认操作', {
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        const params = {
          type: 24,
          status: true,
          name
        };
        createBank(params).then(res => {
          if (res.code === 200) {
            // 新建银行成功回填
            this.backfillBank(name);
            this.getBankList();
            this.$message.success('添加成功');
            this.removeAddNewElement();
          }
        }).catch(err => {
          console.error(err.message);
          this.removeAddNewElement();
          this.bankList = _.cloneDeep(this.bankListTemp);
        });
      }).catch(() => {
        this.backfillBank('');
        this.removeAddNewElement();
        this.bankList = _.cloneDeep(this.bankListTemp);
        return;
      });
    },
    removeAddNewElement() {
      const el = document.querySelector('.create-new-select-item');
      if (el) {
        el.parentNode.removeChild(el);
      }
    }
  }
};
